//
//  EmoticonView.swift
//  表情键盘
//
//  Created by 晁岳山 on 15/10/23.
//  Copyright © 2015年 晁岳山. All rights reserved.
//

import UIKit

class EmoticonView: UIView {
    
    //定义一个闭包  传递点击了的表情到textFiled中 设置内容
    private var emoticonCallBack: (emoticon: Emoticon) -> ()
    
    private let  EmoticonViewCellID = "EmoticonViewCellID"
    private let packages = EmoticonViewManager.sharedManager.packages
    //MARK: - EmoticonView 的构造函数
    init(emoticon: (emoticon: Emoticon) -> ()) {
        emoticonCallBack = emoticon
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        super.init(frame: rect)
//        backgroundColor = UIColor.redColor()
        setupUI()
        //默认选中第一个
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 懒加载控件
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: collecotionLayout())
    
    //MARK: - 自定义layout 类中类  只能在本类中被使用  结构比较清晰
    private class collecotionLayout:UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            //设置属性
            let col: CGFloat = 7
            let row: CGFloat = 3
            let w = UIScreen.mainScreen().bounds.width / col
            let h = (collectionView!.frame.height - w * row) * 0.499
            itemSize =  CGSize(width: w, height: w)
            sectionInset = UIEdgeInsetsMake(h, 0, h, 0)
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.pagingEnabled = true
        }
    }
}

// MARK: - 设置布局
// 使用private修饰extension 内部所有id方法都是私有的
private extension EmoticonView{
  
    func setupUI() {
        //0.设置字体颜色
        toolBar.tintColor = UIColor.darkGrayColor()
        collectionView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        //1.添加控件
        addSubview(toolBar)
        addSubview(collectionView)
        //2.设置自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(self.snp_bottom)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolBar.snp_top)
        }
        //准备控件
        prepareToolBar()
        prepareCollectionView()
    }
    
    //MARK: - 设置toolBar内容
    func prepareToolBar() {
        //设置内容
        var index = 0
        var items = [UIBarButtonItem]()
//        let group_name = EmoticonViewManager.sharedManager.packages
        for name in packages  {
            items.append(UIBarButtonItem(title: name.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickToolBar:"))
            //设置tag
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
    }
    //MARK: - 准备collectionView
    func prepareCollectionView() {
        //注册cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier:EmoticonViewCellID )
        //设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
        
    }
    
    
    //MARK: - UIBarButtonItem 的按钮点击事件
    @objc func clickToolBar(barbuttonItem: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: barbuttonItem.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
}
// MARK: - 实现collectionView的数据源方法
extension EmoticonView: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellID, forIndexPath: indexPath) as! EmoticonViewCell
        //设置内容
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
    //MARK: - collectionView的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let em = packages[indexPath.section].emoticons[indexPath.item]
        emoticonCallBack(emoticon: em)
    }
}
// MARK: - 自定义表情视图cell
private class EmoticonViewCell: UICollectionViewCell{
    
    private lazy var emoticonButton: UIButton = UIButton()
  //在cell中设置数据 一般都封装在cell内容  在cell中直接传个模型就可以啦
    var emoticon: Emoticon? {
        didSet {
            //设置图片
            emoticonButton.setImage(UIImage(contentsOfFile:emoticon!.imagePath), forState: UIControlState.Normal)
            //设置字符串图片
            emoticonButton.setTitle(emoticon!.code, forState: UIControlState.Normal)
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
            emoticonButton.userInteractionEnabled = false
        }
    }
    //MARK: - Cell的构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}